package com.example.demo.controller.ops;

import com.example.camera.CatD;
import com.example.demo.controller.CourseOfflineController;
import com.example.demo.controller.response.ResponsePageData;
import com.example.demo.model.CourseOffline;
import com.example.demo.model.ResposeModel;
import com.example.demo.service.CourseOfflineService;
import com.github.pagehelper.Page;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * Created by Liaopan on 2018/1/25.
 */
@Controller
@RequestMapping("/ops/courseoffline/")
public class CourseOfflineOpsController {

    private static Logger logger = LoggerFactory.getLogger(CourseOfflineController.class);

    @Value("${spring.http.multipart.location}")
    private String uploadFilePath;

    @Autowired
    private CourseOfflineService courseOfflineService;

    /**
     *  ------页面跳转 start-----
     */


    @GetMapping("index")
    public String index(ModelMap modelMap){

        return "ops/courseoffline/index";
    }

    /**
     * 编辑，新增，查看 方法，。
     * @param modelMap
     * @param id
     * @param editFlag edit = 1, new = 0 , show = 2
     * @return
     */
    @GetMapping("edit")
    public String edit(ModelMap modelMap,@RequestParam(value = "id",required = false) Integer id,
                       @RequestParam(value = "flag",defaultValue = "1") Integer editFlag){
        CourseOffline courseOffline = new CourseOffline();
        if(editFlag > 0) {
            courseOffline = courseOfflineService.selectOne(id);
        }
        modelMap.put("courseOffline",courseOffline);
        modelMap.put("edit",editFlag != 2);
        return "ops/courseoffline/edit";
    }

    /**
     *  ------页面跳转 end------
     */


    /**
     * 数据处理
     */

    @GetMapping("data")
    @ResponseBody
    public ResponsePageData data(@RequestParam(value = "page",defaultValue = "1") Integer offset,
                                    @RequestParam(value = "limit",defaultValue = "10") Integer limit,
                                 @RequestParam(value = "filter",required = false) String filter){
        logger.debug("查询条件:"+filter);
        Page<CourseOffline> page = (Page<CourseOffline>)courseOfflineService.selectAll(filter,offset,limit);
        return new ResponsePageData<CourseOffline>(page.getTotal(),page);
    }

    @PostMapping("edit")
    @ResponseBody
    public int edit(CourseOffline courseOffline, @RequestParam("image") MultipartFile file){
        String filePath = saveFile(file);
        CourseOffline re = null;
        if(StringUtils.isNotEmpty(filePath)){ // 文件保存成功
            courseOffline.setImagePath(filePath);
            re = courseOfflineService.createOrUpdate(courseOffline);
        }
        return re != null? 1:0;
    }

    @DeleteMapping("del")
    @ResponseBody
    public int del(@RequestParam("id") Integer id){
        return courseOfflineService.delete(id);
    }


    @RequestMapping(value="/upload", method = RequestMethod.POST)
    public @ResponseBody ResposeModel upload(@RequestParam("file") MultipartFile file,
            HttpServletRequest request) {
        String contentType = file.getContentType();

        String fileName=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+file.getOriginalFilename();
        //String fileName = file.getOriginalFilename();
        String filePath = request.getSession().getServletContext().getRealPath("/imgupload/");
        System.out.println(filePath);
        ResposeModel res = new ResposeModel();
        try {
            CatD.uploadFile(file.getBytes(), filePath, fileName);
            res.setData("/imgupload/"+fileName);
        } catch (Exception e) {
        	e.printStackTrace();
        	res.setStatus("0");
        }

		return res;
    }

    /**
     * 保存图片
     * @param file
     * @return
     */
    public String saveFile(MultipartFile file){
        if(file.isEmpty()){
            return null;
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        logger.debug(fileName + "-->" + size);
        String updateDate = DateFormatUtils.format(new Date(),"yyyy-MM-dd");
        String fileSaveName = String.valueOf(System.currentTimeMillis());

        String fileSavePath = "/" + updateDate + "/" + fileSaveName + "."+
                StringUtils.substringAfterLast(file.getOriginalFilename(),".");

        File dest = new File(uploadFilePath + fileSavePath);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest); //保存文件
            return fileSavePath;
        } catch (IllegalStateException | IOException e) {
            logger.error("保存上传文件出错：",e);
            return null;
        }
    }
}
